﻿using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.ViewEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SysFramework;
using Entity.FrameEntity;

namespace BLL
{
    /// <summary>
    /// 仓库盘点业务逻辑处理层
    /// </summary>
   public class ProCheckBLL : PubMethod
    {
        Commands cmd;
        ReturnResult rsl;
        List<OperateModel> operList;
        OperateModel oper;
        OutBaseHelper outBase;
        public ProCheckBLL()
        {
            cmd = new Commands();
            outBase = new OutBaseHelper();
        }

        /// <summary>
        /// 盘点任务列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult GetTaskList(string pageIndex, string pageSize, ref string pageCount, string condition,string baseCode)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                #region 检索条件
                StringBuilder sb = new StringBuilder();
                string where = "";
                sb.Append(" isdel=0 ");
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (obj.Name == "status")
                            {
                                continue;
                            }
                            if (!string.IsNullOrWhiteSpace(sb.ToString()) && obj.Name != "proName")
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "proName")
                            {
                                where = obj.Value.ToString();
                                continue;
                            }
                            else if (obj.Name == "cStatus")
                            {
                                var sArr = obj.Value.ToString().Split(',');
                                string newSta = "";
                                foreach (string s in sArr)
                                {
                                    if (!string.IsNullOrWhiteSpace(s))
                                    {
                                        newSta += "'" + s + "',";
                                    }
                                }
                                sb.Append(" status in (" + newSta.TrimEnd(',') + ")");
                            }
                            else
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                        }
                    }
                }
                #endregion
                var list = cmd.PageList("V_pch_ProCheckTask_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                
                var newlist = new List<Dictionary<string, string>>();//按存货名字查询后的新列表

                #region 根据存货名称过滤  
                //多行创建一个盘点任务时，由于货位、存货可能是多个，视图关联不出来，所以这再查询一下
                foreach (var item in list)
                {
                    #region where存的是检索条件中的存货名称，按存货名称查时，不包含这个名字的过滤掉
                    if (!string.IsNullOrEmpty(where) && item["proName"].Contains(where))
                    {
                        newlist.Add(item);
                    }
                    #endregion
          
                }
                #endregion

                if (newlist.Count > 0)
                    rsl.Data = newlist;
                else
                    rsl.Data = list;

                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取ERP盘点任务单
        /// </summary>
        /// <returns></returns>
        public ReturnResult GetERPTasks(string condition, string typesCode,string baseCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                var obj = JsonConvert.DeserializeObject<JObject>(condition);
                string chType = obj["chType"].ToString();
                DataTable table = new DataTable();
                if (obj.Property("doType") != null && obj["doType"].ToString() == "on")
                {
                    if (Tools.AppSettingHelper.ReadAppSettings("ConntectERP") != "1")
                    {
                        rsl.Message = "系统为对接ERP，暂时不能获取数据";
                        return rsl;
                    }

                    #region 需要对接ERP 获取ERP系统盘点单sql
                    sb.Clear();
                    sb.Append("select distinct top 50 m.cCVCode erpCode,w.cWhName wareName,m.cWhCode wareCode");
                    if (chType == "pc-position") //货位盘点
                    {
                        sb.Append(",s.cPosition pstCode, po.cPosName pstName");
                    }
                    else if (chType == "pc-pospro")//货位存货盘点
                    {
                        sb.Append(",s.cPosition pstCode, po.cPosName pstName,s.cInvCode proCode, p.cInvName proName");
                    }
                    sb.Append(",Sum(convert(decimal(18,2),iCVQuantity)) number from CheckVouchs s");
                    sb.Append(" inner join CheckVouch m  on m.cCVCode = s.cCVCode and m.dveridate is null ");
                    sb.Append(" inner join Inventory p on p.cInvCode = s.cInvCode ");
                    sb.Append(" inner join Warehouse w on w.cWhCode = m.cWhCode ");
                    sb.Append(" left join Position po on s.cPosition = po.cPosCode and po.cWhCode = w.cWhCode ");
                    sb.Append(" where 1 = 1 ");
                    #region 检索条件
                    if (!string.IsNullOrWhiteSpace(obj["wareCode"].ToString()))
                    {
                        sb.Append(" and m.cWhCode='" + obj["wareCode"].ToString() + "' ");
                    }
                    if (chType == "pc-position" || chType == "pc-pospro")
                    {
                        if (!string.IsNullOrWhiteSpace(obj["pstCode"].ToString()))
                        {
                            sb.Append("and s.cPosition='" + obj["pstCode"].ToString() + "' ");
                        }
                    }

                    #endregion
                    sb.Append(" group by m.cCVCode ,w.cWhName ,m.cWhCode ");
                    if (typesCode == "pc-position") //货位盘点
                    {
                        sb.Append(",s.cPosition , po.cPosName ");
                    }
                    else if (typesCode == "pc-pospro") //货位存货盘点
                    {
                        sb.Append(",s.cPosition, po.cPosName,s.cInvCode");
                        sb.Append(",p.cInvName ");
                    }
                    sb.Append(" order by m.cCVCode desc ");
                    table = outBase.getData(sb.ToString(), baseCode);
                    #endregion 
                }
                else
                {
                    #region 无需对接ERP 获取系统自身库存盘点
                    sb.Clear();
                    sb.Append("select sum(convert(decimal(18,2),isnull(number,'0'))) number,");
                    sb.Append(" count(id) dCount,wareHouse wareCode,houseName wareName");
                    if (chType == "pc-position")
                    {
                        sb.Append(" ,isnull(warePosition,'') pstCode");
                    }
                    else if (chType == "pc-pospro")
                    {//货位存货盘点
                        sb.Append(",warePosition pstCode, proCode,proName");
                    }
                    sb.Append(" from V_BarCode_Info where barStatus='need-out' and status='Y'");
                    #region 检索条件
                    if (!string.IsNullOrWhiteSpace(obj["wareCode"].ToString()) && chType == "pc-ware")
                    {
                        sb.Append(" and wareHouse='" + obj["wareCode"].ToString() + "' ");
                    }
                    else if (chType == "pc-position" )
                    {
                        if (!string.IsNullOrWhiteSpace(obj["wareCode"].ToString()))
                        {
                            sb.Append(" and wareHouse='" + obj["wareCode"].ToString() + "' ");
                        }
                        if (!string.IsNullOrWhiteSpace(obj["pstCode"].ToString()))
                        {
                            sb.Append("and warePosition='" + obj["pstCode"].ToString() + "' ");
                        }
                      
                    }
                    #endregion
                    sb.Append(" group by wareHouse,houseName");
                    if (typesCode == "pc-position") //货位盘点
                    {
                        sb.Append(",isnull(warePosition,'')  ");
                    }
                    else if (typesCode == "pc-pospro") //货位存货盘点
                    {
                        sb.Append(",warePosition,proCode,proName");
                    }
                    table = cmd.GetDataTable(sb.ToString());
                    #endregion
                }


                var list = cmd.TableToDictionary(table);

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 创建盘点任务
        /// </summary>
        /// <param name="datas">数据类型</param>
        /// <param name="chType">检验类型</param>
        /// <param name="userCode"></param>
        /// <param name="baseCode"></param>
        /// <returns></returns>
        public ReturnResult CreateTask(string datas, string chType, string erpCheck,string userCode,string baseCode)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                var dList =JsonConvert.DeserializeObject<List<JObject>>(datas);
               // var dList = JsonConvert.DeserializeObject<List<DbCheckTaskInfo>>(datas);
                StringBuilder sb = new StringBuilder();
                #region 判断是否重复创建盘点任务
                sb.Append("select * from pCh_CheckTask_info where status='pct-doing'");
                sb.Append(" and isdel=0  and chType='"+ chType +"'");
                var mTable = cmd.GetDataTable(sb.ToString());//获取同盘点单 所有未结束的盘点任务
   
                #endregion

                DbCheckTaskInfo chMain = new DbCheckTaskInfo();

                var cArr=CreateCodeInfo("V", "盘点编码", "3",dList.Count).Split(',');
                for (int i=0;i<dList.Count;i++)
                {
                    dList[i].Add("venCode", cArr[i]);
                    if (erpCheck == "Y")
                    {
                        var dr = mTable.Select("erpCode='" + dList[i]["erpCode"].ToString() + "'");
                        if (dr.Length > 0)
                        {
                            rsl.Message = "此盘点单已存在未结束任务，单号：" + dList[i]["erpCode"].ToString();
                            return rsl;
                        }
                    }
                

                    chMain = new DbCheckTaskInfo();
                    chMain.venCode = cArr[i];
                    if (erpCheck == "Y")
                    {
                        chMain.erpCode = dList[i]["erpCode"].ToString();
                    }
                    else
                    {
                        chMain.erpCode = "--";
                    }
                    chMain.erpWareCode = dList[i]["wareCode"].ToString();
                    chMain.chType = chType;
                    chMain.erpCheck = erpCheck;
                    chMain.erpNumber = dList[i]["number"].ToString();
                    if (chType == "pc-position")
                    {
                        if (dList[i].Property("pstCode") == null || string.IsNullOrWhiteSpace(dList[i]["pstCode"].ToString()))
                        {
                            rsl.Message = "盘点为货位盘点时，货位信息不允许为空";
                            return rsl;
                        }
                        chMain.erpPositionCode = dList[i]["pstCode"].ToString();
                        chMain.positionName = dList[i]["pstName"].ToString();
                    }
                    else if(chType == "pc-pospro")
                    {
                        chMain.erpProCode = dList[i]["proCode"].ToString();
                        chMain.proName= dList[i]["proName"].ToString();
                    }
                    chMain.status = "pct-doing";
                    chMain.pchCode = cArr[i];// Guid.NewGuid().ToString().Replace("-", "");
                    chMain.isdel = 0;
                    chMain.createtime = getNow();
                    chMain.createuser = userCode;
                    oper = new OperateModel();
                    oper.Data = chMain;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);
                }
     

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                    if (rsl.Result)
                    { //创建盘点清单
                        this.CreateTaskData(dList, chType, baseCode);
                    }
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 创建盘点清单
        /// </summary>
        /// <returns></returns>
        private ReturnResult CreateTaskData(List<JObject> dList,string chType,string baseCode)
        {
            rsl = new ReturnResult();
            try
            {
                List<string> sqlList = new List<string>();
                StringBuilder sb = new StringBuilder();
                foreach (var obj in dList)
                {
                    sb.Clear();
                    sb.Append("insert into pCh_CheckTask_list");
                    sb.Append(" (barCode,proCode,proName,number,createtime,pchCode,fatherCode) ");
                    sb.Append("select b.barCode,b.proCode,b.proName,number,'" + getNow() + "',");
                    sb.Append("'" + obj["venCode"] + "',''");
                    sb.Append(" from V_BarCode_Info b where ");
                    sb.Append(" barStatus='need-out'   ");
                    if (chType == "pc-ware")
                    {
                        sb.Append("and wareHouse = '" + obj["wareCode"] + "'");
                    }
                    else if (chType == "pc-position")
                    {
                        sb.Append("and wareHouse = '" + obj["wareCode"] + "' and ");
                        sb.Append(" warePosition='" + obj["pstCode"] + "'");
                    }
                    else if (chType == "pc-pospro")
                    {
                        sb.Append("and proCode = '" + obj["proCode"] + "' ");
                    }
                    sqlList.Add(sb.ToString());
                }

                rsl = cmd.MoreUpdate(sqlList);

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 删除盘点任务
        /// </summary>
        /// <param name="pchCode"></param>
        /// <returns></returns>
        public ReturnResult DelCheckTask(string pchCode,string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                List<string> sqlList = new List<string>();
                StringBuilder sb = new StringBuilder();
                sb.Append("update pCh_CheckTask_info set isdel=1");
                sb.Append(",delMsg='" + string.Format("{0}({1})",userCode,getNow()) + "' ");
                sb.Append("where pchCode='" + pchCode + "'");
                sqlList.Add(sb.ToString());
                sb = new StringBuilder();
                sb.Append("delete from pCh_CheckTask_list where pchCode='" + pchCode + "'");
                sqlList.Add(sb.ToString());
                sb = new StringBuilder();
                sb.Append("delete from pCh_CheckTask_records where pchCode='" + pchCode + "'");
                sqlList.Add(sb.ToString());
                rsl = cmd.MoreUpdate(sqlList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 根据盘点存货和仓库列出应盘列表
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="typesCode">盘点编码 </param>
        /// <returns></returns>
        public ReturnResult getYpList(string pageIndex, string pageSize, ref string pageCount, string condition, string typesCode)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                StringBuilder sb = new StringBuilder();
                sb.Append("select l.barCode,s.proCode,s.proName,l.pchCode,l.createtime,s.number num,s.spec ");
                sb.Append(" from pCh_CheckTask_list l left join V_BarCode_Info s on s.barCode = l.barCode ");

                var tableName = sb.ToString();
                sb.Clear();
                sb.Append(" pchCode = '" + typesCode + "'");
                if (!string.IsNullOrWhiteSpace(json["barCode"].ToString()))
                {
                    sb.Append(" and barCode like '%" + json["barCode"].ToString() + "%'");
                }
                if (!string.IsNullOrWhiteSpace(json["proCode"].ToString()))
                {
                    sb.Append(" and proCode='" + json["proCode"].ToString() + "'");
                }
                if (!string.IsNullOrWhiteSpace(json["proName"].ToString()))
                {
                    sb.Append(" and proName like '%" + json["proName"].ToString() + "%'");
                }

                var sqlWhere = sb.ToString();
                var orderStr = " createtime desc ";
                var pageNumber = "0";  //总页数
                var dataTable = cmd.PageTableList(tableName, pageIndex, pageSize, sqlWhere, orderStr, ref pageCount, ref pageNumber);
                rsl.Data = cmd.TableToDictionary(dataTable);
                rsl.Result = true;

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 根据盘点编码获取盘点记录表
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getTaskRecordsByCode(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                StringBuilder sb = new StringBuilder();
       
                var tableName = "V_pCh_CheckTaskRecords";

                sb.Clear();
                sb.Append(" pchCode='" + json["pchCode"] + "' and isdel=0 and status='Y'");

                if (!string.IsNullOrWhiteSpace(json["barCode"].ToString()))
                {
                    sb.Append(" and barCode like '%" + json["barCode"].ToString() + "%'");
                }
                var sqlWhere = sb.ToString();

                var orderStr = " id desc ";
        
                var list = cmd.PageList(tableName, pageIndex, pageSize, sqlWhere, orderStr, ref pageCount);
           

                //rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Data = list;
                rsl.Result = true;

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 更改盘点任务状态
        /// </summary>
        /// <param name="pchCode">盘点单号</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public ReturnResult ChanageStatus(string pchCode, string status)
        {
            rsl = new ReturnResult();
            try
            {
                operList = new List<OperateModel>();
                List<string> sqlList = new List<string>();
                StringBuilder sb = new StringBuilder();
                DbCheckTaskInfo task;
                task = new DbCheckTaskInfo();
                task.pchCode = pchCode;
                task.status = status;
                oper = new OperateModel();
                oper.Data = task;
                oper.Conditions = "pchCode";
                oper.Types = OperateModel.OperateType.Edit;
                operList.Add(oper);
                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 生成盘点报告
        /// </summary>
        /// <param name="pchCodes"></param>
        /// <returns></returns>
        public ReturnResult createReport(string pchCodes,string userCode)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                operList = new List<OperateModel>();
                if (string.IsNullOrWhiteSpace(pchCodes))
                {
                    rsl.Message = "关键参数丢失";
                    return rsl;
                }
                var arr = pchCodes.Split(',');
                List<Dictionary<string, string>> reportList = new List<Dictionary<string, string>>();
                Dictionary<string, string> dic;
                DbCheckTaskReport re;
                DbCheckTaskReportDiffer dif;
                DbCheckTaskInfo task;
                foreach (string code in arr)
                {
                    if (!string.IsNullOrWhiteSpace(code))
                    {

                        StringBuilder sb = new StringBuilder();
                        sb.Append("select * from V_pch_ProCheckTask_info where ");
                        sb.Append(" pchCode='" + code + "'");
                        var taskTable = cmd.GetDataTable(sb.ToString());//获取盘点任务信息
                        sb.Clear();
                        sb.Append("select l.*,b.number from pCh_CheckTask_list l");
                        sb.Append(" inner join bar_ProductBarCode_info b on l.barCode=b.barCode");
                        sb.Append(" where l.pchCode='" + code + "'");
                        var qdTable = cmd.GetDataTable(sb.ToString());//盘点清单(应盘)
                        sb.Clear();
                        sb.Append("select r.*,b.number from pCh_CheckTask_records r");
                        sb.Append(" inner join bar_ProductBarCode_info b on r.barCode=b.barCode");
                        sb.Append(" where r.pchCode='" + code + "' and isdel=0"); // and r.barType='Bar'
                        var rdTable = cmd.GetDataTable(sb.ToString());//盘点记录(实盘)
                        double pkNum = 0, pyNum = 0, ypNum = 0, spNum = 0;//盘亏、盘盈、应盘、实盘
                        List<Dictionary<string, string>> pkList = new List<Dictionary<string, string>>();//盘亏数据集合
                        List<Dictionary<string, string>> pyList = new List<Dictionary<string, string>>();//盘盈数据集合
                        #region 盘亏
                        foreach (DataRow r in qdTable.Rows)
                        {
                            bool ispk = true;
                            foreach (DataRow rd in rdTable.Rows)
                            {
                                if (r["barCode"].ToString() == rd["barCode"].ToString())
                                {
                                    ispk = false;
                                    break;
                                }
                            }
                            if (ispk)
                            {
                                dic = new Dictionary<string, string>();
                                dic["barCode"] = r["barCode"].ToString();
                                dic["number"] = r["number"].ToString();
                                pkNum += double.Parse(r["number1"].ToString());
                                pkList.Add(dic);
                            }

                        }
                        #endregion

                        #region 盘盈
                        foreach (DataRow r in rdTable.Rows)
                        {
                            bool ispy = true;
                            foreach (DataRow rd in qdTable.Rows)
                            {
                                if (r["barCode"].ToString() == rd["barCode"].ToString())
                                {
                                    ispy = false;
                                    break;
                                }
                            }
                            if (ispy)
                            {
                                dic = new Dictionary<string, string>();
                                dic["barCode"] = r["barCode"].ToString();
                                dic["number"] = "1";
                                pyNum += double.Parse(r["number"].ToString());
                                pyList.Add(dic);
                            }

                        }
                        #endregion

                        #region 应盘/实盘
                        foreach (DataRow rd in qdTable.Rows)
                        {
                            ypNum += double.Parse(rd["number1"].ToString());
                        }
                        foreach (DataRow rd in rdTable.Rows)
                        {
                            spNum += double.Parse(rd["number"].ToString());
                        }
                        #endregion

                        #region 盘点报表主表
                        re = new DbCheckTaskReport();
                        re.pchCode = code;//盘点单号
                        re.ypNum = Math.Round(ypNum, 2).ToString();//系统应盘数量
                        re.ypCount = qdTable.Rows.Count.ToString();//系统应盘件数
                        re.spNum = Math.Round(spNum, 2).ToString();
                        re.spCount = rdTable.Rows.Count.ToString();
                        re.pkCount = pkList.Count.ToString();
                        re.pkNum = pkNum.ToString();
                        re.pyCount = pyList.Count.ToString();
                        re.pyNum = pyNum.ToString();
                        re.createtime = getNow();
                        re.createuser = userCode;
                        re.isSync = 0;
                        oper = new OperateModel();
                        oper.Data = re;
                        oper.Types = OperateModel.OperateType.Add;
                        operList.Add(oper);
                        #endregion

                        #region 盘盈/盘亏数据
                        foreach (var d in pkList)
                        {
                            dif = new DbCheckTaskReportDiffer();
                            dif.barCode = d["barCode"].ToString();
                            dif.barType = "Bar";
                            dif.done = "0";
                            dif.pchCode = code;
                            dif.types = "0";
                            oper = new OperateModel();
                            oper.Data = dif;
                            oper.Types = OperateModel.OperateType.Add;
                            operList.Add(oper);
                        }
                        foreach (var d in pyList)
                        {
                            dif = new DbCheckTaskReportDiffer();
                            dif.barCode = d["barCode"].ToString();
                            dif.barType = "Bar";
                            dif.done = "0";
                            dif.pchCode = code;
                            dif.types = "1";
                            oper = new OperateModel();
                            oper.Data = dif;
                            oper.Types = OperateModel.OperateType.Add;
                            operList.Add(oper);
                        }
                        #endregion

                        #region 更改盘点单状态
                        task = new DbCheckTaskInfo();
                        task.pchCode = code;
                        task.status = "pct-report";
                        oper = new OperateModel();
                        oper.Data = task;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "pchCode";
                        operList.Add(oper);
                        #endregion
                    }
                }
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
                else
                {
                    rsl.Message = "没有生成任何数据";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 盘点报告数据列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult TaskReportList(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                StringBuilder sb = new StringBuilder();
                sb.Append(" 1=1 ");
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                        }
                    }
                }
                var list = cmd.PageList("V_pch_proCheckTask_report", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);


                var newlist = new List<Dictionary<string, string>>();//按存货名字查询后的新列表

                if (newlist.Count > 0)
                    rsl.Data = newlist;
                else
                    rsl.Data = list;

                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 获取盘点差异数据
        /// </summary>
        /// <param name="venCode">盘点任务编码</param>
        /// <param name="barType">条码类型 Bar 条码</param>
        /// <param name="types">盈亏类型(1盈 0亏)</param>
        /// <returns></returns>
        public ReturnResult getReportDiffer(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);

                StringBuilder sb = new StringBuilder();
 
                var tableName = "V_pCh_CheckTaskDiffer";

                sb.Clear();
                sb.Append("pchCode='" + json["pchCode"].ToString() + "' and barType='" + json["barType"].ToString() + "' ");
                sb.Append("and types='" + json["typesCode"].ToString() + "'");
                var sqlWhere = sb.ToString();

                var orderStr = " id desc ";
                var list = cmd.PageList(tableName, pageIndex, pageSize, sqlWhere, orderStr, ref pageCount);

                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i]["done"] == "0")
                    {
                        list[i]["done"] = "未处理";
                    }
                    else
                    {
                        list[i]["done"] = "已处理";
                    }
                }
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 删除盘点报告
        /// </summary>
        /// <param name="pchCode">盘点单号</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public ReturnResult delReport(string pchCodes)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {
                if (string.IsNullOrWhiteSpace(pchCodes))
                {
                    rsl.Message = "关键参数丢失";
                    return rsl;
                }
                var arr = pchCodes.Split(',');
                operList = new List<OperateModel>();
                List<string> sqlList = new List<string>();
                foreach (string code in arr)
                {
                    if (!string.IsNullOrWhiteSpace(code))
                    {
                        //删除盘点报告
                        DbCheckTaskReport report;
                        report = new DbCheckTaskReport();
                        report.pchCode = code;
                        oper = new OperateModel();
                        oper.Data = report;
                        oper.Conditions = "pchCode";
                        oper.Types = OperateModel.OperateType.Delete;
                        operList.Add(oper);
                        //修改盘点任务状态
                        DbCheckTaskInfo taskInfo;
                        taskInfo = new DbCheckTaskInfo();
                        taskInfo.pchCode = code;
                        taskInfo.status = "pct-doing";
                        oper = new OperateModel();
                        oper.Data = taskInfo;
                        oper.Conditions = "pchCode";
                        oper.Types = OperateModel.OperateType.Edit;
                        operList.Add(oper);
                        //删除相关盘点差异记录
                        DbCheckTaskReportDiffer diff = new DbCheckTaskReportDiffer();
                        diff.pchCode = code;
                        oper = new OperateModel();
                        oper.Data = diff;
                        oper.Conditions = "pchCode";
                        oper.Types = OperateModel.OperateType.Delete;
                        operList.Add(oper);
                        //将U8中调整出库、调整入库设回默认（0）
                        //sb.Clear();
                        //sb.Append("select re.*,erpId,erpNumber from pCh_CheckTask_report re ");
                        //sb.Append("inner join pCh_CheckTask_info info on re.pchCode=info.pchCode ");
                        //sb.Append("where re.pchCode='" + code + "' ");
                        //var table = cmd.GetDataTable(sb.ToString());
                        //if (table.Rows.Count > 0)
                        //{
                        //    sb.Clear();
                        //    sb.Append("update CheckVouchs set iAdOutQuantity='0',iAdInQuantity ='0' where autoID='" + table.Rows[0]["erpId"] + "'");
                        //}
                        //sqlList.Add(sb.ToString());
                    }
                }

                rsl = cmd.MoreUpdate(operList);
                //if (rsl.Result)
                //    rsl = outBase.TransUpdate(sqlList, null, baseCode);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 更新盘点差异数据信息
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="barType"></param>
        /// <param name="entryType"></param>
        /// <returns></returns>
        public ReturnResult DoCheckDiffers(string ids, string barType, string entryType, string positionCode,string userCode,string baseCode)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            List<string> sqlList = new List<string>();
            List<OperateModel> operList = new List<OperateModel>();
            try
            {
                #region 获取仓库信息
                sb.Append("select erpWareCode,erpPositionCode from pCh_CheckTask_info where pchCode in (");
                sb.Append("select distinct pchCode from pCh_CheckTask_reportDiffer where id in(" + ids + "))");
                var vTable = cmd.GetDataTable(sb.ToString());
                string wareCode = "0", bars = "";  //positionCode="0"
                if (vTable.Rows.Count > 0)
                {
                    wareCode = vTable.Rows[0]["erpWareCode"].ToString();
                    //positionCode = vTable.Rows[0]["erpPositionCode"].ToString();
                }
                #endregion

                #region 获取需要处理的条码信息
                sb.Clear();
                sb.Append("select d.barCode ,b.number from pCh_CheckTask_reportDiffer d ");
                sb.Append(" inner join bar_ProductBarCode_info b on d.barCode=b.barCode ");
                sb.Append(" where d.id in(" + ids + ")");
                var barTable = cmd.GetDataTable(sb.ToString());
                if (barTable.Rows.Count > 0)
                {
                    foreach (DataRow dr in barTable.Rows)
                    {
                        bars = bars + dr["barCode"] + "-" + dr["number"] + ",";
                    }
                }
                #endregion

                #region  新增出入库记录 、 修改条码状态信息
                #region 获取出入库编码
                string mcode = DateTime.Now.ToString("yyyyMMddhhmmss");
                #endregion

                #region 主表添加
                //sb.Clear();
                //sb.Append("insert into bar_BarEntryRecords_main(mCode,mType,happenDate,wareHouse,maker,createtime,createuser,status,deptCode,");
                //sb.Append("outOrderCode,memo,isForm,inOutType,baseCode,isBlue,goodsPosition) values ('"+ mCode + "','11','"+);
                DbBarRecordsMain main = new DbBarRecordsMain();
                main.mCode = mcode;
                main.mType = "11";
                main.happenDate = DateTime.Now.ToString("yyyy-MM-dd");
                main.wareHouse = wareCode;
                main.maker = userCode;
                main.createtime = DateTime.Now.ToString();
                main.createuser = userCode;
                main.status = "needAudit";
                //main.deptCode = ;
                //main.outOrderCode = ;
                main.memo = "盘点差异调整";
                main.isForm = "PC";
                if (entryType == "1")//盘亏 做出库
                    //main.inOutType = "pitz";
                    main.inOutType = "potz";
                else
                    //main.inOutType = "potz";
                    main.inOutType = "pitz";
                main.baseCode = baseCode;
                main.isBlue = "1";
                main.goodsPosition = positionCode;

                oper = new OperateModel();
                oper.Data = main;
                oper.Types = OperateModel.OperateType.Add;
                operList.Add(oper);
                #endregion

                foreach (string s in bars.TrimEnd(',').Split(','))
                {
                    #region  子表添加
                    DbBarRecordsList dbList = new DbBarRecordsList();
                    dbList.mCode = mcode;
                    dbList.barCode = s.Split('-')[0];
                    dbList.num = s.Split('-')[1];
                    dbList.status = "Y";
                    dbList.createtime = DateTime.Now.ToString();
                    dbList.createuser = userCode;
                    if (entryType == "1")
                        dbList.inOutType = "potz";
                    else
                        dbList.inOutType = "pitz";

                    oper = new OperateModel();
                    oper.Data = dbList;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);
                    #endregion

                    #region 条码 仓库、货位、状态修改
                    DbProductBarCode bar = new DbProductBarCode();
                    bar.wareHouse = wareCode;
                    bar.warePosition = positionCode;
                    bar.memo = "盘点差异处理  " + getNow() + "(" + userCode + ")";
                    if (entryType == "1")//盘亏 做出库
                        bar.barStatus = "bar-finish";
                    else
                        bar.barStatus = "need-out";

                    bar.barCode = s.Split('-')[0];

                    oper = new OperateModel();
                    oper.Data = bar;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "barCode";
                    operList.Add(oper);

                    #endregion
                }
                #endregion

                #region 修改条码差异为已处理
                foreach (string s in ids.Split(','))
                {
                    DbCheckTaskReportDiffer dif = new DbCheckTaskReportDiffer();
                    dif.id = Convert.ToInt32(s);
                    dif.done = "1";
                    dif.memo = getNow() + "(" + userCode + ")";

                    oper = new OperateModel();
                    oper.Data = dif;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                    operList.Add(oper);
                }

                #endregion

                rsl = cmd.MoreUpdate(operList);

                if (rsl.Result)
                {
                    
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 同步盘点结果
        /// </summary>
        /// <returns></returns>
        public ReturnResult syncReport(string pchCodes,string baseCode)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            List<string> erpList = new List<string>();
            List<string> sqlList = new List<string>();

            try
            {
                if (string.IsNullOrWhiteSpace(pchCodes))
                {
                    rsl.Message = "关键参数丢失";
                    return rsl;
                }

                var errMsg = "";
                var pCarr = pchCodes.Split(',');

                if (Tools.AppSettingHelper.ReadAppSettings("ConntectERP") != "1")
                {
                    rsl.Message = "系统未对接ERP，无法禁止同步结果";
                    return rsl;
                }
                #region 获取配置参数
                sb.Clear();
                sb.Append("select * from sys_parameters_info where parCode='venPar'");//编码固定
                var parTable = cmd.GetDataTable(sb.ToString());
                List<JObject> setList=new List<JObject>();
                string keyFileds = "";
                if (parTable.Rows.Count > 0 && !string.IsNullOrWhiteSpace(parTable.Rows[0]["parValue"].ToString()))
                {//[{"erpCode":"","sysCode":""},...]
                    setList = JsonConvert.DeserializeObject<List<JObject>>(parTable.Rows[0]["parValue"].ToString());
                    foreach (var obj in setList)
                    {
                        keyFileds += string.Format("b.{0},", obj["sysCode"].ToString());
                    }
                }
                #endregion

                foreach (string code in pCarr)
                {
                    #region 报告已同步 不再同步
                    sb.Clear();
                    sb.Append("select isSync,venCode,erpCheck from V_pch_proCheckTask_report ");
                    sb.Append("where pchCode ='" + code + "'");
                    var rptable = cmd.GetDataTable(sb.ToString());
                    if (rptable.Rows[0][0].ToString().Equals("1"))
                    {
                        rsl.Message =  "系统禁止重复同步盘点结果，单号："+ rptable.Rows[0]["venCode"].ToString();
                        continue;
                    }
                    if (rptable.Rows[0]["erpCheck"].ToString() == "N")
                    {
                        rsl.Message = "盘点单结果不能同步ERP，单号："+ rptable.Rows[0]["venCode"].ToString();
                        return rsl;
                    }
                    #endregion

                    #region 判断盘点是否还有数据未进行差异调整
                    sb.Clear();
                    sb.Append("select top 1 id from pCh_CheckTask_reportDiffer where ");
                    sb.Append(" pchCode = '" + code + "' and done=0");
                    var yk_Table = cmd.GetDataTable(sb.ToString());
                    if (yk_Table.Rows.Count > 0)
                    {
                        rsl.Result = false;
                        rsl.Message = "盘点差异未进行调整，数据不能同步,任务："+code;
                        return rsl;
                    }
                    #endregion


                    #region 获取盘点货位、盘点存货和盘点类型
                    sb.Clear();
                    sb.Append("select erpCode,isnull(erpPositionCode,'') erpPositionCode,chType,erpWareCode ");
                    sb.Append("from pCh_CheckTask_info where pchCode='" + code + "'");
                    var table = cmd.GetDataTable(sb.ToString()); //盘点单主表信息
                    string erpPosition = table.Rows[0]["erpPositionCode"].ToString();//盘点货位
                    string wareCode = table.Rows[0]["erpWareCode"].ToString();//仓库编码
                    string chType = table.Rows[0]["chType"].ToString();//盘点类型
                    string erpCode = table.Rows[0]["erpCode"].ToString();//关联盘点单号


                    #endregion

                    /**
                    实盘记录与实际库存相一致，所以可以将实盘记录条码作为最终的盘点结果
                    【盘亏：账面条码做出库，盘盈：关联条码做入库(实盘已盘)】
                     **/////////////
                    #region 获取当前盘点单关联条码信息
                    sb.Clear();
                    sb.Append("select proCode,sum(convert(decimal(18,2),isnull(r.number,'0'))) number,");
                    sb.Append("count(r.barCode) barCount");
                    string whStr = "";
             
                    if (!string.IsNullOrWhiteSpace(keyFileds))
                    {
                        sb.Append("," + keyFileds.Trim(','));
                        whStr += "," + keyFileds;
                    }
                    sb.Append(" from pCh_CheckTask_records r inner join bar_ProductBarCode_info b on ");
                    sb.Append("r.barCode=b.barCode where pchCode='"+ code + "' and r.isdel=0");
                    sb.Append(" group by proCode");
                    if (!string.IsNullOrWhiteSpace(whStr))
                    {
                        sb.Append(whStr.TrimEnd(','));
                    }
                   
                    var kcTable = cmd.GetDataTable(sb.ToString());
                    #endregion
   
                    #region 获取erp盘点单子表
                    sb.Clear();
                    sb.Append("select * from CheckVouchs where cCVCode='" + erpCode + "' ");
    
                    var erp_s_table = outBase.getData(sb.ToString(), baseCode);//U8盘点单子表
                   
                    if (erp_s_table.Rows.Count < 1)
                    {
                        rsl.Message = "盘点单(" + erpCode + ")不存在或已删除，同步失败！";
                        return rsl;
                    }
                    #endregion

                    #region erp单据id表
                    sb.Clear();
                    sb.Append("select * from UFSystem.dbo.UA_Identity where cVouchType = 'ch'");
                    sb.Append(" and cAcc_Id = '" + baseCode + "'");
                    var idTable = outBase.getData(sb.ToString(), baseCode);// 单据id表
                    var iChildId = int.Parse(idTable.Rows[0]["iChildId"].ToString());
                    var autoID = int.Parse("1" + idTable.Rows[0]["iChildId"].ToString().PadLeft(9, '0'));
                    #endregion

                    bool isAdd = false;
                    foreach (DataRow r in kcTable.Rows)
                    {
                        sb.Clear();
                        sb.Append("cInvCode='" + r["proCode"].ToString() + "'");
                        if (!string.IsNullOrWhiteSpace(erpPosition))
                        {
                            sb.Append(" and cPosition='"+ erpPosition +"'");
                        }
                        foreach (var obj in setList)
                        {
                            sb.Append(string.Format(" and {0}='{1}'", obj["erpCode"].ToString(), r[obj["sysCode"].ToString()].ToString()));
                        }
                        var dr = erp_s_table.Select(sb.ToString());
                        var rowNo = int.Parse(erp_s_table.Rows[erp_s_table.Rows.Count - 1]["irowno"].ToString());
                        var erp_id = erp_s_table.Rows[0]["ID"].ToString();
                        if (dr.Length > 0)
                        {
                            #region 盘点单存在，直接修改数量
                            sb.Clear();
                            sb.Append("update CheckVouchs set iCVCQuantity ='" + r["number"].ToString() + "'");
                            sb.Append(",iCVCNum ='" + r["barCount"].ToString() + "' ");
                            if (double.Parse(dr[0]["iCVQuantity"].ToString()) <= 0)
                            {
                                foreach (var obj in setList)
                                {
                                    sb.Append(string.Format(",{0}='{1}'", obj["erpCode"].ToString(), r[obj["sysCode"].ToString()].ToString()));
                                }
                            }
                            sb.Append(" where autoID='" + dr[0]["autoID"] + "'");
                            erpList.Add(sb.ToString());
                            #endregion
                        }
                        else
                        {
                            #region 盘点单不存在实盘单数据，需要在U8盘点单新增数据
                            isAdd = true;

                            #region 直接新增行
                            autoID += 1;
                            iChildId += 1;
                            rowNo += 1;
                            var cbsysbarcode = "||st18|" + erpCode + "|" + rowNo;

                            sb.Clear();
                            //物控有 U8没有  在U8新增行
                            //iCVQuantity 账面数量， iCVNum 账面辅计量数量（件数）， iCVCNum 盘点辅计量数量 ，iCVCQuantity 盘点数量（实盘数） 
                            sb.Append("insert into CheckVouchs(cCVCode,cInvCode,iCVNum,iCVQuantity,iCVCNum,iCVCQuantity,");
                            sb.Append("autoID,ID,iAdInQuantity,iAdInNum,iAdOutQuantity,iAdOutNum,");
                            sb.Append("irowno,cbsysbarcode,cbufts");
                            string dValues = "";
                            foreach (var s in setList)
                            {
                                if (!string.IsNullOrWhiteSpace(s["erpCode"].ToString()))
                                {
                                    sb.Append(","+ s["erpCode"].ToString().Trim());
                                    if (!string.IsNullOrWhiteSpace(r[s["sysCode"].ToString().Trim()].ToString()))
                                    {
                                        dValues += "," + r[s["sysCode"].ToString().Trim()].ToString();
                                    }
                                    else
                                    {
                                        dValues += ",''" ;
                                    }
                                }
                            }
                            sb.Append(")");
                            sb.Append("values('" + erpCode + "','" + r["proCode"].ToString() + "',0,0,");
                            sb.Append("'"+r["barCount"].ToString()+"','" + r["number"].ToString() + "',");
                            sb.Append("'" + autoID + "','" + erp_id);
                            sb.Append("',0,0,0,0,'" + rowNo + "','" + cbsysbarcode);
                            sb.Append("',DEFAULT");
                            if (!string.IsNullOrWhiteSpace(dValues))
                            {
                                sb.Append(dValues);
                            }
                            sb.Append(")");
                            #endregion

                            erpList.Add(sb.ToString());

                     
                            #endregion
                        }
                    }

                    if (isAdd)
                    {
                        sb.Clear();
                        sb.Append("update UFSystem.dbo.UA_Identity set iChildId='" + iChildId + "' where cVouchType='ch' ");
                        sb.Append("and cAcc_Id='" + baseCode + "'");
                        erpList.Add(sb.ToString());
                    }
                    #region 盘亏处理
                    /**
                     以U8盘点单子表为准(货位存货盘点时 只看盘点的存货)，查找物控实盘列表，
                     如果U8有物控没有，则修改调整出库
                     **/
                    foreach (DataRow dr in erp_s_table.Rows)
                    {
                        sb.Clear();
                        sb.Append("proCode='" + dr["cInvCode"].ToString() + "'");
                        if (!string.IsNullOrWhiteSpace(erpPosition))
                        {
                            sb.Append(" and erpPosition='" + erpPosition + "'");
                        }
                        foreach (var obj in setList)
                        {
                            sb.Append(string.Format(" and {0}='{1}'", obj["sysCode"].ToString(), dr[obj["erpCode"].ToString().Trim()].ToString()));
                        }
                        var qr = kcTable.Select(sb.ToString());
                        if (qr.Length < 1)
                        {
                            sb.Clear();
                            sb.Append("update CheckVouchs set iCVCQuantity ='0',iCVCNum ='0'");
                            //if (double.Parse(dr["iCVQuantity"].ToString()) <= 0)
                            //{
                                //foreach (var obj in setList)
                                //{
                                //    sb.Append(string.Format(",{0}='{1}'", obj["erpCode"].ToString(), qr[0][obj["sysCode"].ToString()].ToString()));
                                //}
                            //}
                            sb.Append(" where autoID='" + dr["autoID"] + "'");
                            erpList.Add(sb.ToString());
                        }
                        


                    }
                    #endregion

                    #region 设置盘点报告同步状态
                    sb.Clear();
                    sb.Append("update pCh_CheckTask_report set isSync='1' where pchCode='"+ code +"'");
                    sqlList.Add(sb.ToString());
                    #endregion

            

                    if (erpList.Count > 0)
                    {
                        rsl = outBase.TransUpdate(erpList, null, baseCode);
                        if (rsl.Result)
                        {
                            rsl = cmd.MoreUpdate(sqlList);
                        }
                    }
                    else
                    {
                        rsl = cmd.MoreUpdate(sqlList);
                    }
                       
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
           
            }
            return rsl;
        }


        /// <summary>
        /// 获取实盘存货统计数
        /// </summary>
        /// <param name="pchCode">盘点标识码</param>
        /// <param name="pstCode">货位编码</param>
        /// <param name="errMsg">错误消息</param>
        /// <returns></returns>
        public DataTable getSPProsTotal(string pchCode,string pstCode, ref string keyFileds, ref string errMsg)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from sys_parameters_info where parCode='venPar'");//编码固定
                var parTable = cmd.GetDataTable(sb.ToString());
                keyFileds = "";
                if (parTable.Rows.Count > 0 && !string.IsNullOrWhiteSpace(parTable.Rows[0]["parValue"].ToString()))
                {//[{"erpCode":"","sysCode":""},...]
                    var list = JsonConvert.DeserializeObject<List<JObject>>(parTable.Rows[0]["parValue"].ToString());
                    foreach (var obj in list)
                    {
                        keyFileds += string.Format("b.{0},", obj["sysCode"].ToString());
                    }
                }
                sb.Clear();
                sb.Append("select sum(CONVERT(decimal(18,2),b.number)) number");
                if (!string.IsNullOrWhiteSpace(pstCode))
                {
                    sb.Append(",isnull(b.warePosition,'') warePosition");
                }
                keyFileds = keyFileds.TrimEnd(',');
                if (string.IsNullOrWhiteSpace(keyFileds))
                {
                    sb.Append(","+keyFileds);
                }
                sb.Append(",proCode from pCh_CheckTask_records rd");
                sb.Append("  inner join bar_ProductBarCode_info b on b.barCode=rd.barCode");
                if (!string.IsNullOrWhiteSpace(pchCode))
                {
                    sb.Append("where rd.pchCode='" + pchCode + "'");
                }
                sb.Append(" group by b.proCode ");
                if (!string.IsNullOrWhiteSpace(pstCode))
                {
                    sb.Append(",b.warePosition");
                }
                if (string.IsNullOrWhiteSpace(keyFileds))
                {
                    sb.Append("," + keyFileds);
                }
                var table = cmd.GetDataTable(sb.ToString()); //实盘列表
                return table;
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                return null;
            }
        }

        /// <summary>
        ///查询U8货位现存量
        /// </summary>
        /// <returns></returns>
        public DataTable getPosSum(string posCode,string baseCode, ref string errMsg)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from InvPositionSum ");
                if (!string.IsNullOrWhiteSpace(posCode))
                {
                    sb.Append("where cPosCode = '" + posCode + "'");
                }
                var table = outBase.getData(sb.ToString(), baseCode);//U8货位存量
                return table;
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                return null;
            }
        }

        /// <summary>
        ///查询物控货位现存量
        /// </summary>
        /// <returns></returns>
        public DataTable getBarPosSum(string posCode, ref string errMsg)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select warePosition,proCode,number from bar_ProductBarCode_info where barStatus = 'need-out' ");
                if (!string.IsNullOrWhiteSpace(posCode))
                {
                    sb.Append("and warePosition = '" + posCode + "' ");
                }
                var table = cmd.GetDataTable(sb.ToString()); //物控货位存量
                return table;
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                return null;
            }
        }


        /// <summary>
        /// 盘点记录信息保存(移动端H5)
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult AddTaskRecord(string datas)
        {
            rsl = new ReturnResult();
            DbCheckTaskRecords re;
            try
            {
                List<OperateModel> list = new List<OperateModel>();
                OperateModel oper;
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                if (string.IsNullOrWhiteSpace(json["pchCode"].ToString()))
                {
                    rsl.Message = "盘点编码不能为空";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();

                #region 盘点编码验证
                sb.Append("select *,erpProCode proCode from pCh_CheckTask_info where ");
                sb.Append("pchCode='" + json["pchCode"].ToString() + "' and ");
                sb.Append("isdel=0 and status='pct-doing' and venCode='" + json["pdCode"].ToString() + "' ");
                var venTable = cmd.GetDataTable(sb.ToString());
                if (venTable.Rows.Count < 1)
                {
                    rsl.Message = "盘点单号无效";
                    return rsl;
                }
                #endregion

                #region 重复盘点
                sb.Clear();
                sb.Append("select barCode from pCh_CheckTask_records where ");
                sb.Append(" pchCode='" + json["pchCode"].ToString() + "'");
                sb.Append(" and barCode='" + json["barCode"].ToString() + "'");
                var qTable = cmd.GetDataTable(sb.ToString());
                if (qTable.Rows.Count > 0)
                {
                    rsl.Message = "条码已存在记录,禁止重复盘点";
                    return rsl;
                }
                #endregion

                #region 条码信息显示
                List<Dictionary<string, string>> barList = new List<Dictionary<string, string>>();
                sb.Clear();
                sb.Append("select * from bar_ProductBarCode_info where barCode='" + json["barCode"].ToString() + "'");
                var barTable = cmd.GetDataTable(sb.ToString());
                if (barTable.Rows.Count > 0)
                {
                    if (!string.IsNullOrWhiteSpace(venTable.Rows[0]["proCode"].ToString()))
                    {
                        var arr = barTable.Rows[0]["proCode"].ToString().Split(',');
                        var varr = venTable.Rows[0]["proCode"].ToString().Split(',');
                        if (varr != null && varr.Length > 0)
                        {
                            var flag = false;//是否存在盘点任务里面的存货
                            foreach (var vProCode in varr)
                            {
                                if (string.IsNullOrWhiteSpace(vProCode))
                                {
                                    continue;
                                }
                                if (arr != null && arr.Length > 0)
                                {
                                    foreach (var proCode in arr)
                                    {
                                        if (string.IsNullOrWhiteSpace(proCode))
                                        {
                                            continue;
                                        }
                                        if (vProCode.Equals(proCode))
                                        {
                                            flag = true;
                                        }
                                    }

                                }
                            }
                            if (!flag)
                            {
                                rsl.Result = false;
                                rsl.Message = "此码不是所盘存货类型";
                                return rsl;
                            }
                        }


                    }
                    barList = cmd.TableToDictionary(barTable);
                }
                else
                {
                    rsl.Result = false;
                    rsl.Message = "此码为无效码";
                    return rsl;
                }
                #endregion

                #region 记录保存
                re = new DbCheckTaskRecords();
                re.pchCode = json["pchCode"].ToString();
                re.barCode = json["barCode"].ToString();
                //re.number= json["number"].ToString();
                re.number= barList[0]["number"].ToString();
				re.isdel = 0;
                re.createtime = getNow();
                re.createuser = json["createuser"].ToString();
                re.Id = Guid.NewGuid().ToString().ToLower().Replace("-", "");
                re.status = "Y";
                oper = new OperateModel();
                oper.Data = re;
                oper.Types = OperateModel.OperateType.Add;
                list.Add(oper);
                #endregion

                if (list.Count > 0)
                {
                    rsl = cmd.MoreUpdate(list);
                    if (rsl.Result)
                    {
                        sb.Clear();
                        sb.Append("select * from pCh_CheckTask_records where pchCode='" + json["pchCode"].ToString() + "' and status='Y' ");
                        barTable = cmd.GetDataTable(sb.ToString());
                        var dic = new Dictionary<string, object>();
                        var barNumber = 0;
                        if (barTable != null && barTable.Rows.Count > 0)
                        {
                            barNumber = barTable.Rows.Count;
                        }
                        dic.Add("barNumber", barNumber);
                        rsl.Data = dic;
                    }
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 获取全部有效的盘点记录(移动端)
        /// </summary>
        /// <returns></returns>
        public ReturnResult getInventoryList(string jsonStr)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Message = "传入的参数不能为空";
                    rsl.Result = false;
                    return rsl;
                }
                string barCodes = string.Empty;
                var json = JsonConvert.DeserializeObject<JObject>(jsonStr);
                StringBuilder sb = new StringBuilder();
                var dicList = new Dictionary<string, object>();
                DbCheckTaskRecords venTaskRecord = new DbCheckTaskRecords();
                sb.Append("select barCode from pCh_CheckTask_records ");
                sb.Append(" where pchCode = '" + json["pchCode"].ToString() + "' and isdel=0");
                var dt = cmd.GetDataTable(sb.ToString());
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow item in dt.Rows)
                    {
                        barCodes += "'" + item[0] + "'" + ",";
                    }
                }
                sb.Clear();
                if (barCodes.Length <= 0)
                {
                    rsl.Message = "无数据";
                    rsl.Result = false;
                    return rsl;
                }
                sb.Append(" select * from bar_ProductBarCode_info");
                sb.Append(" where barCode in(" + barCodes.TrimEnd(',') + ") ");
                dt = cmd.GetDataTable(sb.ToString());
                var list = cmd.TableToDictionary(dt);
                if (json.Property("mobType") != null && !string.IsNullOrWhiteSpace(json["mobType"].ToString()) && json["mobType"].ToString().Equals("H5"))
                {
                    #region 构建列表数据
                    #region 构建列表元素显示格式
                    var headList = new List<object>();
                    var hList = new List<Dictionary<string, string>>();
                    createHead(ref hList, "barCode", "条码号");
                    headList.Add(hList);
                    //hList = new List<Dictionary<string, string>>();
                    //createHead(ref hList, "proCode", "存货编码");
                    //createHead(ref hList, "proName", "存货名称");
                    //headList.Add(hList);
                    hList = new List<Dictionary<string, string>>();
                    //createHead(ref hList, "proStyle", "存货类型");
                    createHead(ref hList, "planCode", "生产计划单");
                    headList.Add(hList);
                    hList = new List<Dictionary<string, string>>();
                    createHead(ref hList, "number", "数量");
                    createHead(ref hList, "proWeight", "重量");
                    headList.Add(hList);
                    hList = new List<Dictionary<string, string>>();
                    createHead(ref hList, "proCode", "存货编码");
                    createHead(ref hList, "proName", "存货名称");
                    headList.Add(hList);
                    #endregion
                    var listInfo = new Dictionary<string, object>();
                    #region 数据分页显示
                    //总条数
                    var pageCount = "0";
                    //总页数
                    var pageNumber = "0";
                    //每页条数
                    var pageSize = "20";
                    var paraList = cmd.getParam("appPageSize");
                    if (paraList != null && paraList.Count > 0)
                    {
                        if (!string.IsNullOrWhiteSpace(paraList[0].parValue))
                        {
                            pageSize = paraList[0].parValue;
                        }
                    }
                    var table = cmd.PageTableList(dt, json["pageIndex"].ToString(), pageSize, ref pageCount, ref pageNumber);
                    var listDt = new DataTable();
                    var temlist = cmd.TableToDictionary(table);

                    listInfo.Add("head", headList);
                    listInfo.Add("list", temlist);

                    #endregion

                    listInfo.Add("pageNumber", pageNumber);
                    var pageIndex = int.Parse(json["pageIndex"].ToString());
                    listInfo.Add("pageIndex", pageIndex.ToString());
                    dicList.Add("listInfo", listInfo);
                    #endregion

                    #region 构建汇总数据
                    headList = new List<object>();
                    hList = new List<Dictionary<string, string>>();
                    createHead(ref hList, "count", "总件数");
                    createHead(ref hList, "number", "总数量");
                    headList.Add(hList);
                    #region 汇总列表中信息
                    var sumDic = new Dictionary<string, string>();
                    var number = 0m;
                    var count = 0;
                    //var weight = 0.0m;
                    //var meter = 0.0m;

                    if (list != null && list.Count > 0)
                    {
                        foreach (var item in list)
                        {
                            var proNumber = item["number"].ToString();
                            //var proWeight = item["proWeight"].ToString();
                            if (!string.IsNullOrWhiteSpace(proNumber) && Convert.ToDecimal(proNumber) > 0)
                            {
                                number += decimal.Parse(proNumber);
                            }
                            //if (!string.IsNullOrWhiteSpace(proWeight) && Convert.ToDecimal(proWeight) > 0)
                            //{
                            //    weight += Convert.ToDecimal(proWeight);
                            //}
                        }
                        count = list.Count;
                    }
                    sumDic.Add("count", count.ToString());
                    sumDic.Add("number", number.ToString());
                    //sumDic.Add("weight", Convert.ToDecimal(weight).ToString("F2"));
                    var sumDicList = new List<Dictionary<string, string>>();
                    sumDicList.Add(sumDic);
                    #endregion
                    var sumList = new Dictionary<string, object>();
                    sumList.Add("head", headList);
                    sumList.Add("list", sumDicList);
                    dicList.Add("sumList", sumList);
                    #endregion
                }
                rsl.Data = dicList;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Result = false;
                rsl.Message = ex.Message;
            }
            return rsl;
        }

    }
}
